package com.frontop.terminal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.entity.PlayList;
import com.frontop.terminal.model.bo.TerminalResourceBO;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.service.ICommandSerivce;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.WriteDataUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 修改资源名称
 * </p>
 *
 * @author Frontop
 * @since :2022-06-28
 **/
@Slf4j
public class PlayerUpdateResourceNameServiceImpl implements ICommandSerivce {

    /**
     * 执行业务
     *
     * @param message 消息对象
     * @return T
     */
    @SuppressWarnings({"ConstantConditions"})
    @Override
    public RestResult executeWork(Message message) {

        TerminalResourceBO resourceBO = JSON.parseObject(message.getCommand(), TerminalResourceBO.class);

        if (ObjectUtil.isNull(resourceBO)) {
            return RestResult.failed("返回的数据异常,转换对象失败");
        }

        var playListMap = ReadDataUtil.getPlayListMap();

        if (null != playListMap && !playListMap.isEmpty()) {
            PlayList play = playListMap.get(Long.valueOf(resourceBO.getId()));
            if (null == play) {
                log.warn("要修改名称的资源不存在:{}", message.getCommand());
                return RestResult.failed("要修改名称的资源不存在");
            }

            play.setName(resourceBO.getResourceName());

            List<PlayList> playLists = new ArrayList<>(playListMap.values());
            //保存
            WriteDataUtil.write(playLists, ReadDataUtil.PLAYLIST_LIST_CODING);
        }
        return RestResult.success();
    }
}
